<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		
		<script type="module">
			import '../lib/js/face-api.min.js';
			import { loadRandomImage } from "../lib/js/util.js";
			(async function() {
				
				// 加载模型
				await faceapi.nets.tinyFaceDetector.loadFromUri("../models");
				const image = await loadRandomImage();
				document.body.append(image);
				// 使用模型
				const faces = await faceapi.detectAllFaces(image, new faceapi.TinyFaceDetectorOptions());
				const box = {
				  // 将边界设置为它们的逆无穷大，因此任何数字都更大/更小
				  bottom: -Infinity,
				  left: Infinity,
				  right: -Infinity,
				  top: Infinity,
				
				  // 给出边界，我们可以计算出宽度和高度
				  get height() {
				    return this.bottom - this.top;
				  },
				
				  get width() {
				    return this.right - this.left;
				  },
				};
				// 未检测到人脸
				if (faces.length === 0) {
					document.body.append("未检测到人脸😶");
					return;
				}
				
				// 更新 box 的边界
				for (const face of faces) {
				  box.bottom = Math.max(box.bottom, face.box.bottom);
				  box.left = Math.min(box.left, face.box.left);
				  box.right = Math.max(box.right, face.box.right);
				  box.top = Math.min(box.top, face.box.top);
				}
				// 显示到页面
				const canvas = document.createElement('canvas');
				const context = canvas.getContext('2d');
				
				canvas.height = box.height;
				canvas.width = box.width;
				
				context.drawImage(
				  image,
				  box.left,
				  box.top,
				  box.width,
				  box.height,
				  0,
				  0,
				  canvas.width,
				  canvas.height
				);
				document.body.append(canvas);
			})();
		</script>
	</body>
</html>